//
//  TL_ReportAlertView.m
//  WXReader
//
//  Created by Andrew on 2021/12/8.
//  Copyright © 2021 Andrew. All rights reserved.
//

#import "TL_ReportAlertView.h"
#import "TL_PayFailModel.h"
#import "TL_ReportTableViewCell.h"
#import "UIView+LayoutCallback.h"

@interface TL_ReportAlertView () <UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource>
{
    UIView *backView;
    UILabel *mainTitleLabel;
    UIButton *closeButton;
    
    UITableView *mainTableView;

    UIActivityIndicatorView *loadingIndicatorView;
    
    NSInteger selectedIndex;
}

@property (nonatomic, strong) TL_PayFailModel *payFailModel;

@end

@implementation TL_ReportAlertView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self createSubviews];
    }
    return self;
}

- (void)createSubviews
{
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    self.alpha = 0;
    [kMainWindow addSubview:self];
    
    if (!self.superview) {
        UIViewController *vc = [UIApplication sharedApplication].windows.firstObject.rootViewController;
        [vc.view addSubview:self];
    }
    
    UITapGestureRecognizer *dismissTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenAlertView)];
    dismissTapGesture.numberOfTapsRequired = 1;
    dismissTapGesture.delegate = self;
    [self addGestureRecognizer:dismissTapGesture];
    
    selectedIndex = 0;
    
    backView = [TL_UIFactory viewWithBackgroundColor:kWhiteColor cornerRadius:0];
    backView.userInteractionEnabled = YES;
    backView.frameBlock = ^(UIView * _Nonnull view) {
        [view setCorner:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadius:10];
    };
    [self addSubview:backView];
    
    mainTitleLabel = [TL_UIFactory labelWithBackgroundColor:UIColor.clearColor font:kMainFont textColor:kBlackColor];
    mainTitleLabel.text = WXLocalizedString(@"投诉");
    mainTitleLabel.textAlignment = NSTextAlignmentCenter;
    mainTitleLabel.userInteractionEnabled = YES;
    [backView addSubview:mainTitleLabel];
    
    [mainTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mas_centerX);
        make.top.mas_equalTo(backView.mas_top);
        make.width.mas_equalTo(backView.mas_width);
        make.height.mas_equalTo(40);
    }];
    
    UIView *line = [TL_UIFactory view];
    line.backgroundColor = kGrayLineColor;
    [backView addSubview:line];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kHalfMargin);
        make.top.mas_equalTo(mainTitleLabel.mas_bottom);
        make.width.mas_equalTo(backView.mas_width).with.offset(- kMargin);
        make.height.mas_equalTo(kCellLineHeight);
    }];
    
    closeButton = [TL_UIFactory buttonWithTarget:self action:@selector(hiddenAlertView)];
    closeButton.tintColor = RGB(153, 153, 153);
    [closeButton setImageEdgeInsets:UIEdgeInsetsMake(18, 36, 18, 0)];
    [closeButton setImage:[[UIImage imageNamed:@"public_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [backView addSubview:closeButton];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(backView.mas_right).with.offset(- kHalfMargin);
        make.centerY.mas_equalTo(mainTitleLabel.mas_centerY);
        make.width.height.mas_equalTo(50);
    }];
    
    mainTableView = [TL_UIFactory tableViewWithBackgroundColor:kWhiteColor delegate:self style:UITableViewStylePlain cellClass:@[]];
    [backView addSubview:mainTableView];
    
    [mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(mainTitleLabel.mas_bottom).with.offset(kHalfMargin);
        make.width.mas_equalTo(backView.mas_width);
        make.height.mas_equalTo(100);
    }];
    
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(self.mas_bottom).with.offset(- kHalfMargin);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.bottom.mas_equalTo(mainTableView.mas_bottom).with.offset(kHalfMargin + PUB_TABBAR_OFFSET);
    }];
    
    loadingIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    loadingIndicatorView.color = kBlackColor;
    loadingIndicatorView.hidesWhenStopped = YES;
    [loadingIndicatorView startAnimating];
    [backView addSubview:loadingIndicatorView];
    
    [loadingIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(backView.mas_centerX);
        make.centerY.mas_equalTo(backView.mas_centerY);
        make.width.height.mas_equalTo(20);
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.payFailModel.options.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TL_ReportTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TL_ReportTableViewCell"];
    
    if (!cell) {
        cell = [[TL_ReportTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TL_ReportTableViewCell"];
    }

    cell.payFailListModel = [self.payFailModel.options objectAtIndex:indexPath.row];
    cell.hiddenEndLine = NO;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TL_PayFailListModel *listModel = [self.payFailModel.options objectAtIndex:indexPath.row];
    
    if (self.reportSuccessBlock) {
        self.reportSuccessBlock();
    }
    
    
//    [TL_NetworkRequestManger POST:Report_Comment parameters:@{@"content_type":(self.productionType == TL_ProductionTypeBook?@"1":@"2"), @"book_id":[TL_UtilsHelper formatStringWithInteger:self.book_id], @"comment_id":[TL_UtilsHelper formatStringWithInteger:self.comment_id], @"reason_type":[TL_UtilsHelper formatStringWithInteger:listModel.reason_type]} model:nil success:^(BOOL isSuccess, id  _Nullable t_model, TL_NetworkRequestModel * _Nonnull requestModel) {
//        if (isSuccess) {
//            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"举报成功")];
//        } else {
//            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
//        [TL_TopAlertManager showAlertWithError:error defaultText:@""];
//    }];
    
    [self hiddenAlertView];
}

- (void)showAlertView
{
    mainTableView.hidden = YES;

    [self networkRequest];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:kAnimatedDurationFast animations:^{
            [backView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.mas_bottom).with.offset(- 200);
            }];
            [backView.superview layoutIfNeeded];
            self.alpha = 1;
        }];
    });
}

- (void)hiddenAlertView
{
    [UIView animateWithDuration:kAnimatedDurationFast animations:^{
        [backView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_bottom);
        }];
        [backView.superview layoutIfNeeded];
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeAllSubviews];
        [self removeFromSuperview];
    }];
}

- (void)setPayFailModel:(TL_PayFailModel *)payFailModel
{
    _payFailModel = payFailModel;
    if (payFailModel) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:kAnimatedDurationFast animations:^{
                [backView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self.mas_bottom).with.offset(- (40 + payFailModel.options.count * 44 + 2 * kHalfMargin + PUB_TABBAR_OFFSET));
                }];
                [backView.superview layoutIfNeeded];
            }];
        });
        
        mainTitleLabel.text = payFailModel.title?:@"";
        
        [loadingIndicatorView stopAnimating];
        
        mainTableView.hidden = NO;
        [mainTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(payFailModel.options.count * 44);
        }];
        
        [mainTableView reloadData];
    }
}

- (void)networkRequest
{
//    [TL_NetworkRequestManger POST:Report_Pupup parameters:@{@"content_type":(self.productionType == TL_ProductionTypeBook?@"1":@"2")} model:TL_PayFailModel.class success:^(BOOL isSuccess, TL_PayFailModel *t_model, TL_NetworkRequestModel * _Nonnull requestModel) {
//        if (isSuccess) {
//            self.payFailModel = t_model;
//        } else {
//            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
//            [self hiddenAlertView];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
//        [TL_TopAlertManager showAlertWithError:error defaultText:@""];
//        [self hiddenAlertView];
//    }];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isEqual:self]) {
        return YES;
    } else {
        return NO;
    }
}

@end
